﻿using Microsoft.EntityFrameworkCore;

namespace StarsAdmin.Core.DB.Extension
{
    public static class TransactionExtension
    {
        public static bool NewTransaction(this DbContext context, Action action)
        {
            using var transaction = context.Database.BeginTransaction();
            try
            {
                action?.Invoke();
                transaction.Commit();
                return true;
            } catch
            {
                transaction.Rollback();
                throw;
            } finally
            {
                // 确保即使发生异常，也能处理事务
                transaction.Dispose();
            }
        }

        public static async Task<bool> NewTransactionAsync(this DbContext context, Func<Task> func)
        {
            using var transaction = await context.Database.BeginTransactionAsync();
            try
            {
                await func.Invoke();
                await transaction.CommitAsync();
                return true;
            } catch
            {
                await transaction.RollbackAsync();
                throw;
            } finally
            {
                // 确保即使发生异常，也能处理事务
                await transaction.DisposeAsync();
            }
        }
    }
}